package com.hetang.maijiayun.adaptertools.utils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.dataformat.xml.JacksonXmlAnnotationIntrospector;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class XmlUtil {
	private static XmlMapper xm;
	
	static {		
		xm = new XmlMapper();
		xm.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		xm.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		xm.setAnnotationIntrospector(new JacksonXmlAnnotationIntrospector());
	}
	
	public static <T> T getBean(String xml, Class<T> clazz) throws AdapterException {
		if(xml == null || xml.isEmpty())
			return null;

		try {
			return xm.readValue(xml, clazz);
		} catch (JsonParseException e) {
			throw new AdapterException(AdapterExceptionErrorCode.JSON_ERROR_CODE, e.getMessage());
		} catch (JsonMappingException e) {
			throw new AdapterException(AdapterExceptionErrorCode.JSON_ERROR_CODE, e.getMessage());
		} catch (IOException e) {
			throw new AdapterException(AdapterExceptionErrorCode.JSON_ERROR_CODE, e.getMessage());
		}
	}
	
	/**
	 * 
	 * LFQ 2014-8-1 下午6:52:18 
	 * @param xml
	 * @param clazz
	 * @param pattern 用于指定转换Date类型属性时的格式化串
	 * @return
	 * @throws AdapterException
	 */
	public static <T> T getBean(String xml, Class<T> clazz, String pattern) throws AdapterException {
		if(xml == null || xml.isEmpty())
			return null;
		if(pattern.isEmpty()){
			throw new AdapterException("invalid parameter. pattern cant be empty.");
		}
		try {
			XmlMapper xm = new XmlMapper();
			xm.setDateFormat(new SimpleDateFormat(pattern));
			xm.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			xm.setAnnotationIntrospector(new JacksonXmlAnnotationIntrospector());
			return xm.readValue(xml, clazz);
		} catch (JsonParseException e) {
			throw new AdapterException(AdapterExceptionErrorCode.JSON_ERROR_CODE, e.getMessage());
		} catch (JsonMappingException e) {
			throw new AdapterException(AdapterExceptionErrorCode.JSON_ERROR_CODE, e.getMessage());
		} catch (IOException e) {
			throw new AdapterException(AdapterExceptionErrorCode.JSON_ERROR_CODE, e.getMessage());
		}
	}

	public static String writeAsString(Object t) throws AdapterException {
		try {
			return xm.writeValueAsString(t);
		} catch (JsonProcessingException e) {
			throw new AdapterException(AdapterExceptionErrorCode.JSON_ERROR_CODE, e.getMessage());
		}
	}
}